import axios from 'axios'
import { UseUIStore } from '@/store/UI';
import { getToken } from './auth';
import { showToast } from 'vant';
import { SId } from './index';
import route from '@/router';

const server = axios.create({
    baseURL: import.meta.env.VITE_APP_API_HOST,
    timeout: 90 * 1000
})

server.defaults.headers.post['Content-Type'] = 'spplication/json';
server.interceptors.request.use((config) => {
    config.withCredentials = true;
    const token = getToken();
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
}, (error) => {
    console.error(error);
    return Promise.reject(error);
})

// http request 拦截器
server.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code == '20000') {
            return res;
        } else if (res.code == 'SYS00000063' || res.code == "SYS00000088") {
            // Go login
            route.push('/login');
        } else {
            if (typeof res.message == 'string') {
                showToast(res.message)
            };
        }
    },
    //接口错误状态处理，也就是说无响应时的处理
    error => {
        if (error.response.status == 400) {
            showToast('参数错误，请检查参数信息');
        } else if (error.response.status == 403) {
            showToast('服务器出现错误，请检查参数信息');
        } else if (error.response.status == 404) {
            showToast('未找到接口，请检查链接地址');
        } else if (error.response.status == 500) {
            showToast('服务器出现错误');
        } else if (error.response.status == 502) {
            showToast('服务器响应出现错误');
        } else if (error.response.status == 503) {
            showToast('服务器正在重启，请稍后...');
        } else {
            showToast('链接异常，请检查错误信息(' + error.response.status + ')');
        }
        return Promise.reject(error) // 返回接口返回的错误信息
    })

let AxiosEventCatch = {};

/**
 * 隐藏 loading 方法
 *
 * @param {*} id
 * @memberof Request
 */
const hideLoading = function (id) {
    delete AxiosEventCatch[id];
    if (Object.keys(AxiosEventCatch).length == 0) {
        UseUIStore().loading = false;
    }
}

const Event = function (options) {
    var id = SId();
    if (options.loading !== false) {
        AxiosEventCatch[id] = '';
        UseUIStore().loading = true;
    }
    // 将/user/{userId} 格式化到 params 参数中
    var _params = JSON.parse(JSON.stringify(options.params));
    var _url = options.url.replace(/\{\w+\}/g, function (i) {
        var _src = i.replace('{', '').replace('}', '');
        if (_params.hasOwnProperty(_src)) {
            var _value = _params[_src];
            delete _params[_src];
            return _value;
        }
    });
    return server({
        method: options.type,
        url: _url,
        params: _params,
        data: options.data
    }).finally(function () {
        if (options.loading !== false) {
            hideLoading(id);
        }
    });
}

export default {
    /**
     * apis 接口调用参数
     *
     * @param {String} url  链接地址
     * @param {Object} params Url 传参对象
     * @param {Object} data PostData 传参对象
     * @param {Object} option 选项   option.loading 是否显示loading option.BaseUrl 自定义前缀,只在调试模式下使用
     * @return {axios} 接口异步对象
     */
    post(url, params, data, option = {}) {
        var _data = {};
        _data.type = 'post';
        _data.data = data || {};
        _data.params = params;
        _data.url = url;
        _data.reqType = option.reqType;
        _data.loading = option.loading;
        return Event(_data)
    },
    get(url, params, data, option = {}) {
        var _data = {};
        _data.type = 'get';
        _data.data = data || {};
        _data.params = params;
        _data.url = url;
        _data.reqType = option.reqType;
        _data.loading = option.loading;
        return Event(_data)
    },
    put(url, params, data, option = {}) {
        var _data = {};
        _data.type = 'put';
        _data.data = data || {};
        _data.params = params;
        _data.url = url;
        _data.reqType = option.reqType;
        _data.loading = option.loading;
        return Event(_data)
    },
    delete(url, params, data, option = {}) {
        var _data = {};
        _data.type = 'delete';
        _data.data = data || {};
        _data.params = params;
        _data.url = url;
        _data.reqType = option.reqType;
        _data.loading = option.loading;
        return Event(_data)
    }
}

